#include "IterativeDeepeningSearch.h"


IterativeDeepeningSearch::IterativeDeepeningSearch(void)
{
}


IterativeDeepeningSearch::~IterativeDeepeningSearch(void)
{
}

const char* IterativeDeepeningSearch::getFileName() {
	return "IterativeDeepeningSearch.gpi";
}

void IterativeDeepeningSearch::performSearch(node* start, node* goal, Grapher* gr, bool penalized, int maxExpandVectors) {
	node* current = NULL;
	node* next = NULL;
	edge* e = NULL;
	queue_node qn;
	
	int depth = 0;
	int secondCount = 0;
	bool goalReached = false;

	while(!goalReached){
		g->clearFlags();
		goal->isGoal = true;
		stack.push(queue_node::newQN(0, start));
		while(!stack.empty()) {
			qn = stack.top();
			stack.pop();

			current = qn.graph_node;

			if (current->isGoal){
				goalReached=true;
				break;
			}
			if (current->flag == 1) continue;

			current->flag = 1;

			if (gr != NULL && current->previous != NULL) {
				gr->addVector(Vector2(current->previous->x, current->previous->y), Vector2(current->x, current->y), 3);
			}

			if(current->cost == depth) continue;

			for(int i = current->neighbors.size()-1; i >= 0; i --){
				e = &current->neighbors[i];
				next = e->to;
			
				if(next->flag == 1) continue;

				next->previous = current;
				next->cost = current->cost+1;
				stack.push(queue_node::newQN(next->cost, qn.pathCost + e->weight, next));
			}

			secondCount ++;
			if(maxExpandVectors > 0 && secondCount >= maxExpandVectors) {
				goalReached = true;
				break;
			}
			if(secondCount % 1000 == 0)
				std::cout  << "Expanded " << secondCount << " nodes\n";
		}
		std::cout << secondCount << endl;
		gr->clearVertexBuffer();
		depth+=1000;
	}

	goal->isGoal = false;
}
